import React, {useState, useEffect, useRef} from 'react';
import axios from "axios";
import {PageHeader, Steps, Button, Form, Input, Select, message, notification, Descriptions} from 'antd'
import style from './NewsAdd.module.css';
import NewsEditor from '../../../components/news-manage/NewsEditor';

const {Step} = Steps;
const {Option} = Select;

export default function NewsAdd(props) {

    const [Current, setCurrent] = useState(0)
    const [categories, setCategories] = useState([])
    const [newsHeaderInfo, setNewsHeaderInfo] = useState('')
    const [NewsContent, setNewsContent] = useState('')

    const newsForm = useRef(null)

    const Token = JSON.parse(localStorage.getItem('token'))

    useEffect(() => {
        axios.get('/categories').then(res => {
            console.log(res.data)
            setCategories(res.data)
        })
    }, [])

    const onChange = current => {
        setCurrent(current)
    };

    const handleLastStep = (auditState) => {
        axios.post('/news', {
            ...newsHeaderInfo,
            "content": NewsContent,
            "region": Token.region === '' ? "全球" : Token.region,
            "author": Token.username,
            "roleId": Token.roleId,
            "auditState": auditState,
            "publishState": 0,
            "createTime": Date.now(),
            "star": 0,
            "view": 0,
            // "publishTime": 1615778496314
        }).then(() => {
            // 通知成功
            notification.success({
                message: '恭喜您！',
                description:
                    auditState === 0 ? '保存草稿成功，您可以在【新闻管理/草稿箱】中查看' : '提交审核成功，您可以在【新闻管理/审核列表】中查看',
            });
            // 跳转到相应页面
            props.history.push(auditState === 0 ? '/news-manage/draft' : '/audit-manage/list')
        })
    }

    const getCategory = (categories) => {
        const Category =  categories.filter(item => item.id === newsHeaderInfo.categoryId)
        return Category[0]?.title
    }

    return (
        <div>
            {/* 页头 */}
            <PageHeader
                title="撰写新闻"
                // subTitle="This is a subtitle"  // 副标题
            />

            {/* 步骤条 */}
            <Steps
                type="navigation"
                current={Current}
                onChange={onChange}
                className={style.siteNavigationSteps}
            >
                <Step title="基本信息" description="新闻标题与分类"/>
                <Step title="新闻内容" description="新闻主体内容"/>
                <Step title="新闻提交" description="保存草稿或提交审核"/>
            </Steps>

            {/* 内容区 */}
            {/* 第一步内容 */}
            <div className={Current === 0 ? '' : style.hidde}>
                <Form
                    ref={newsForm}
                    name="basic"
                    autoComplete="off"
                >
                    <Form.Item
                        label="新闻标题"
                        name="title"
                        rules={[{required: true, message: '请输入新闻标题'}]}
                    >
                        <Input/>
                    </Form.Item>

                    <Form.Item
                        label="新闻分类"
                        name="categoryId"
                        rules={[{required: true, message: '请选择新闻分类'}]}
                    >
                        <Select>
                            {categories.map(item =>
                                <Option value={item.id} key={item.id}>{item.title}</Option>
                            )}
                        </Select>
                    </Form.Item>
                </Form>
            </div>
            {/* 第二步内容 */}
            <div className={Current === 1 ? '' : style.hidde}>
                <NewsEditor getEditorContent={(value) => {
                    // console.log(value)
                    // 将新闻内容储存起来
                    setNewsContent(value)
                }}/>
            </div>
            {/* 第三步内容 */}
            {categories && <div className={Current === 2 ? '' : style.hidde}>
                <div className={style.PageHeaderBox}>
                    <PageHeader
                        ghost={false}
                        title={newsHeaderInfo.title}
                    >
                        <Descriptions size="small" column={2}>
                            <Descriptions.Item label="作者">{Token.username}</Descriptions.Item>
                            <Descriptions.Item label="身份">{Token.role.roleName}</Descriptions.Item>
                            <Descriptions.Item label="栏目">{getCategory(categories)}</Descriptions.Item>
                            <Descriptions.Item label="区域">{Token.region ? Token.region : '全球'}</Descriptions.Item>
                        </Descriptions>
                    </PageHeader>
                    {/* 新闻内容 */}
                    <div className={style.NewsConent} dangerouslySetInnerHTML={{
                        __html:NewsContent
                    }}>
                        {/*<p>hykfghdhfg</p>*/}
                    </div>
                </div>
            </div>}

            {/* 按钮区 */}
            <div className={style.btn}>
                {
                    Current === 0 && <Button type='primary' disabled>上一步</Button>
                }
                {
                    Current > 0 && <Button type='primary' ghost onClick={() => {
                        setCurrent(Current - 1)
                    }}>上一步</Button>
                }
                {
                    Current < 2 && <Button type="primary" onClick={() => {
                        // 步骤1时，按下一步需要校验表单
                        if (Current === 0) {
                            newsForm.current.validateFields().then(res => {
                                console.log(res)
                                // 将新闻标题和分类存储
                                setNewsHeaderInfo(res)

                                setCurrent(Current + 1)
                            }).catch(error => {
                                console.log(error)
                            })
                        } else if (Current === 1 && (NewsContent.trim() === '<p></p>' || NewsContent === '')) {    // 新闻内容为空时，禁止跳到下一步，并提示
                            message.error('新闻内容不能为空').then()
                            console.log(NewsContent)
                        } else {
                            setCurrent(Current + 1)
                        }

                    }}>下一步</Button>
                }
                {
                    Current === 2 && <span>
                        <Button type="primary" onClick={() => handleLastStep(0)}>保存草稿</Button>
                        <Button className={style.audit} type='primary' onClick={() => handleLastStep(1)}>提交审核</Button>
                    </span>
                }
            </div>
        </div>
    )
}